package cn.shop.cloud.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: work
 * @ClassName CookieUtils
 * @description:
 * @author: 李尧坤
 * @create: 2025−01-08 14:46
 * @Version 1.0
 **/

public class CookieUtil {
    //防止写错 变成常量
    public static  final String TOKEN_COOKIE_NAME="userToken";
    public static  final int TOKEN_EXPIR_TIME=1800;

    /**
     * 添加信息到浏览器的 cookie中
     * @param response
     * @param cookieName
     * @param cookieValue
     * @param expireSeconds
     */
    public static  void addCookie(HttpServletResponse response, String cookieName, String cookieValue, int expireSeconds){
        Cookie cookie = new Cookie(cookieName,cookieValue);//创建cookie
        //设置你的作用区域
        cookie.setDomain("localhost");
        cookie.setPath("/");
        cookie.setMaxAge(expireSeconds);//过期时间
        //借助response将信息写入浏览器
        response.addCookie(cookie);
    }

    /**
     * 获取cookie
     * @param request
     * @param tokenCookieName
     * @return
     */
    public static String getCookie(HttpServletRequest request, String tokenCookieName) {
        // 浏览器可能存很多个cookie
        Cookie[] cookies = request.getCookies();

        if(cookies!=null && cookies.length>0){
            //有数据
            for (Cookie cookie:cookies){
                if(cookie.getName().equals(tokenCookieName)){
                    //找到了你要的cookie
                    return  cookie.getValue();
                }
            }
        }
        return  null;
    }

}
